package com.nvwa.coding.util.trace;

import org.slf4j.MDC;

import java.util.UUID;

public class TraceHolder {
    /**
     * 追踪ID
     */
    public static final String TRACE_ID = "traceId";

    public TraceHolder() {
    }

    public static void set(String traceId) {
        MDC.put(TRACE_ID, traceId);
    }

    public static String get() {
        return MDC.get(TRACE_ID);
    }

    public static String make() {
        String traceId = TraceIdGenerator.generateTraceId();
        set(traceId);
        return traceId;
    }

    public static String getOrMake() {
        String traceId = get();
        return traceId == null ? make() : traceId;
    }

    public static void clear() {
        MDC.clear();
    }

    private static class TraceIdGenerator {
        public static String generateTraceId() {
            String u = UUID.randomUUID().toString();
            return u.split("-")[4];
        }
    }
}